<template>
  <px-card shadow="never">
    <div class="flex-row">
      <div style="display: flex">
        <px-button v-has="'SYSTEM_BASE_POSITION_MANAGE_ADD'" type="primary" icon="Plus" style="margin-right: 8px" @click="handleAdd"
          >新增位置</px-button
        >
        <px-button
          v-has="'SYSTEM_BASE_POSITION_MANAGE_DOWNLOAD'"
          style="margin-left: 0; margin-right: 8px"
          type="primary"
          plain
          @click="templateDownload"
          >下载模板</px-button
        >
        <BatchUpload url="/ifp/digitaltwins/api/v1/position/importData" permission="SYSTEM_BASE_POSITION_MANAGE_UPLOAD" @updateUploadPage="getList" />
      </div>
      <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="68px">
        <px-form-item label="位置名称" prop="name">
          <px-input v-model="queryParams.name" placeholder="请输入位置名称" clearable @keyup.enter="getList">
            <template #suffix>
              <px-icon style="cursor: pointer" @click="getList">
                <search />
              </px-icon>
            </template>
          </px-input>
        </px-form-item>
        <px-button style="margin-top: -16px" type="primary" @click="getList">查询</px-button>
        <px-button style="margin-top: -16px" @click="resetQuery">重置</px-button>
      </px-form>
    </div>

    <px-table
      v-loading="loading"
      class="custom-table"
      border
      row-key="id"
      :data="tableData"
      :tree-props="{ children: 'children', hasChildren: true }"
    >
      <px-table-column label="位置名称" prop="name" min-width="160" show-overflow-tooltip />
      <px-table-column label="位置类型" prop="typeDesc" min-width="100" show-overflow-tooltip />
      <px-table-column label="区域负责人" prop="principalName" min-width="160" show-overflow-tooltip>
        <template #default="scope">
          <template v-if="scope.row.principalNameList && scope.row.principalNameList.length > 0">
            <px-tag v-for="(item, index) in scope.row.principalNameList" :key="index" style="margin-right: 8px">
              {{ item }}
            </px-tag>
          </template>
          <span v-else>-</span>
        </template>
      </px-table-column>
      <px-table-column label="创建人" prop="createByName" min-width="100" show-overflow-tooltip />
      <px-table-column label="创建时间" prop="createTime" min-width="100" />
      <px-table-column label="操作" width="150">
        <template #default="scope">
          <px-tooltip v-if="scope.row.parentCode !== '0'" content="编辑" placement="top">
            <px-button v-has="'SYSTEM_BASE_POSITION_MANAGE_ADD'" link type="primary" icon="Edit" @click="handleEdit(scope.row)" />
          </px-tooltip>
          <px-tooltip content="添加位置" placement="top">
            <px-button v-has="'SYSTEM_BASE_POSITION_MANAGE_EDIT'" link type="primary" icon="Plus" @click="handleAddChildren(scope.row)" />
          </px-tooltip>
          <px-tooltip v-if="scope.row.parentCode !== '0'" content="删除" placement="top">
            <px-button v-has="'SYSTEM_BASE_POSITION_MANAGE_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
    <!-- 添加或修改参数配置对话框 -->
    <px-drawer
      v-model="open"
      :close-on-click-modal="false"
      :title="formValue.id ? '修改位置' : '新增位置'"
      width="600px"
      destroy-on-close
      append-to-body
      @close="cancel"
    >
      <px-form ref="positionRef" :model="formValue" :rules="rules" label-width="120px">
        <px-form-item label="父级位置" prop="parentCode">
          <px-tree-select
            v-model="formValue.parentCode"
            style="width: 100%"
            :disabled="!formValue.id && isChild"
            :data="parentOptions"
            :props="defaultProps"
            node-key="id"
            check-strictly
            :render-after-expand="false"
            placeholder="请选择所属父级"
            filterable
            clearable
            @node-click="handleNodeClick"
          />
        </px-form-item>
        <px-form-item label="位置名称" prop="name">
          <px-input v-model="formValue.name" maxlength="50" clearable placeholder="请输入位置名称" />
        </px-form-item>
        <px-form-item label="位置类型" prop="type">
          <px-select v-model="formValue.type" style="width: 100%" clearable filterable>
            <px-option v-for="item in typeList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="科室" prop="className">
          <px-select v-model="formValue.className" style="width: 100%" clearable filterable @change="changeClassName">
            <px-option v-for="item in classNameList" :key="item.id" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="区域负责人" prop="principalIdList">
          <px-select-v2
            v-model="formValue.principalIdList"
            style="width: 100%"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            filterable
            clearable
            :options="principalList"
            placeholder="请输入区域负责人"
            @focus="focusPrincipalList"
          />
        </px-form-item>
        <px-form-item label="排序" prop="orderSeq">
          <px-input-number v-model="formValue.orderSeq" :min="0" />
        </px-form-item>
      </px-form>
      <template #footer>
        <div class="dialog-footer">
          <px-button type="primary" @click="submitForm">确 定</px-button>
          <px-button @click="cancel">取 消</px-button>
        </div>
      </template>
    </px-drawer>
  </px-card>
</template>

<script setup lang="ts">
defineOptions({
  name: "SYSTEM_BASE_POSITION_MANAGE"
});
import { queryDictData } from "@/api/common";
import { addData, deleteData, editData, getPositionData } from "@/api/system/positionManage";
import BatchUpload from "@/components/Upload/BatchUpload.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";
const { proxy }: any = getCurrentInstance();

const open = ref(false);
const loading = ref(true);

const defaultProps = {
  children: "children",
  label: "name",
  id: "facCode"
};

const data = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined
  },
  formValue: {
    orderSeq: 0
  },
  rules: {
    parentCode: [{ required: true, message: "父级位置不能为空", trigger: "blur" }],
    name: [{ required: true, message: "位置名称不能为空", trigger: "blur" }],
    type: [{ required: true, message: "位置类型不能为空", trigger: "blur" }]
  },
  principalList: [],
  tableData: [],
  typeList: [],
  classNameList: [],
  parentOptions: [],
  isChild: false,
  facCode: "" // 厂区编码
});

const { queryParams, formValue, rules, principalList, tableData, typeList, classNameList, parentOptions, isChild, facCode } = toRefs(data);

/** 查询位置信息列表 */
const getList = async () => {
  loading.value = true;
  const data: any = await getPositionData(queryParams.value);
  tableData.value = addPropertyToTree(data);
  parentOptions.value = data;
  loading.value = false;
};

const handleGetDictData = async () => {
  const data = await queryDictData({ typeCode: "fac_position_type" });
  typeList.value = data.filter(item => item.value !== "FAC"); // 厂区只能在数据字典添加
  classNameList.value = await queryDictData({ typeCode: "className" });
};

const handleNodeClick = val => {
  facCode.value = val.facCode;
};

onMounted(async () => {
  await getList();
  await handleGetDictData();
});

// 获取当前科室负责人接口
const focusPrincipalList = async () => {
  const param = formValue.value.className ? [formValue.value.className] : [];
  const data = await getEmployeeIdAndName(param);
  principalList.value = JSON.parse(JSON.stringify(data));
};
// 修改科室时，清空负责人
const changeClassName = () => {
  formValue.value.principalIdList = [];
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  proxy.resetForm("positionRef");
  facCode.value = "";
  formValue.value = {
    orderSeq: 0
  };
  isChild.value = false;
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  getList();
};
/** 新增按钮操作 */
const handleAdd = () => {
  open.value = true;
};
const handleAddChildren = (row: any) => {
  formValue.value.parentCode = row.code;
  facCode.value = row.facCode;
  isChild.value = true;
  open.value = true;
};
/** 修改按钮操作 */
const handleEdit = row => {
  formValue.value = JSON.parse(JSON.stringify(row));
  formValue.value.principalIdList = row?.principalIds?.split(",").map(Number) || [];
  facCode.value = row.facCode;
  focusPrincipalList();
  open.value = true;
};
/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["positionRef"].validate(valid => {
    if (valid) {
      formValue.value.principalNameList = principalList.value
        .filter(item => formValue.value.principalIdList.includes(item.userId))
        .map(item => item.username + "-" + item.realName);
      if (formValue.value.id) {
        editData(formValue.value).then(() => {
          PxMessage.success("修改成功");
          getList();
        });
      } else {
        addData({ facCode: facCode.value, ...formValue.value }).then(() => {
          PxMessage.success("新增成功");
          getList();
        });
      }
      cancel();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = row => {
  const { name, id } = row;
  PxMessageBox.confirm(`是否确认删除位置名称为${name}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteData({ id });
      PxMessage.success("删除成功");
      getList();
    })
    .catch(() => {});
};
// 下载模版
const templateDownload = async () => {
  proxy.download("get", "/digitaltwins/api/v1/position/templateDownLoad", {}, "设备位置模板.xlsx");
};
const addPropertyToTree = nodes => {
  // 遍历每个节点
  for (const node of nodes) {
    node["principalNameList"] = node.principalNames?.split(",") || [];
    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      addPropertyToTree(node.children);
    }
  }
  return nodes;
};
</script>

<style scoped>
.flex-row {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: space-between;
}
</style>
